<?php
class Controller{
	protected $__vars = array();
	public function assign($k,$v){
		$this->__vars[$k] = $v;
	}
	public function display($path){
		extract($this->__vars);
        define("INCLUDE_PATH",APP_DIR."Templates/".ucfirst($_ENV['_G'])."/");
        $path = INCLUDE_PATH.str_replace("Controller","",ucfirst(get_class($this)))."/".$path.".php";
        if(file_exists($path)){
            if(defined("LAYOUT_HEADER")){
                include INCLUDE_PATH.LAYOUT_HEADER.".php";
            }
            include $path;
            if(defined("LAYOUT_FOOTER")){
                include INCLUDE_PATH.LAYOUT_FOOTER.".php";
            }
        }else{
            echo $path."不存在";
        }
		die();
	}
	public function json(){
		$var = array("code" => 0 , 'msg' => "" , "data" => $this->__vars );
		echo json_encode($var);
		die();
	}
	public function __call($name,$args){
		$this->error(1);
	}
	public function error($code){
		echo $code;die();
	}

	/**
	 * 判断用户是不是post
	 */
	public function isPost(){
		return $_SERVER['REQUEST_METHOD'] == 'POST';
	}
	public function get($k,$def = null,$func = null){
		if(isset($_GET[$k])){
			if($func){
				return $func($_GET[$k]);
			}else{
				return $_GET[$k];
			}
		}
		return $def;
	}
	public function post($k,$def = null,$func = null){
		if(isset($_POST[$k])){
			if($func){
				return $func($_POST[$k]);
			}else{
				return $_POST[$k];
			}
		}
		return $def;
	}
	public function req($k,$def = null,$func = null){
		if(isset($_REQUEST[$k])){
			if($func){
				return $func($_REQUEST[$k]);
			}else{
				return $_REQUEST[$k];
			}
		}
		return $def;
	}
	/**
	 * 获取用户的ip地址
	 */
	public function getIP(){
		$ip = "Unknown";
		if ($HTTP_SERVER_VARS["HTTP_X_FORWARDED_FOR"])
		{
			$ip = $HTTP_SERVER_VARS["HTTP_X_FORWARDED_FOR"];
		}
		elseif ($HTTP_SERVER_VARS["HTTP_CLIENT_IP"])
		{
			$ip = $HTTP_SERVER_VARS["HTTP_CLIENT_IP"];
		}
		elseif ($HTTP_SERVER_VARS["REMOTE_ADDR"])
		{
			$ip = $HTTP_SERVER_VARS["REMOTE_ADDR"];
		}
		elseif (getenv("HTTP_X_FORWARDED_FOR"))
		{
		$ip = getenv("HTTP_X_FORWARDED_FOR");
			}
		elseif (getenv("HTTP_CLIENT_IP"))
		{
			$ip = getenv("HTTP_CLIENT_IP");
		}
		elseif(getenv("REMOTE_ADDR"))
		{
			$ip = getenv("REMOTE_ADDR");
		}
		return $ip;
	}

}
